<?php
namespace Admin\Controller;
/**
 * 文章分类控制器
 */
class CategoriesController extends BaseController{
	/**
	 * 管理文章分类首页
	 */
	public function index(){
		$this->categories=M('categories')->select();
		$this->title='文章分类管理';
		$this->display();
	}

	/**
	 * 添加文章分类
	 */
	public function add(){
		if(IS_AJAX){
			$cate=trim(I('post.category'));
            if($cate==''){
                $this->ajaxReturn(array('status'=>0,'msg'=>'分类为空'));
            }
            $categoryInfo=M('categories')->where('category="'.$cate.'"')->find();
            if(!$categoryInfo){
            	//添加分类
                M('categories')->add(array('category'=>ucfirst($cate),'create_time'=>time()));
                $this->ajaxReturn(array('status'=>1,'msg'=>'分类已保存'));
            }else{
            	$this->ajaxReturn(array('status'=>0,'msg'=>'分类已存在'));
            }
		}else{
			$this->error('访问错误');
		}
	}

	/**
	 * 删除文章分类
	 */
	public function delete(){
		if(IS_AJAX && !empty(I('post.id'))){
			if(M('articles')->where(array('category_id'=>I('post.id')))->find()){
				$this->ajaxReturn(array('status'=>0,'msg'=>'该分类有文章，不能删除'));
			}
			if(M('categories')->delete(I('post.id'))){
	            $this->ajaxReturn(array('status'=>1,'msg'=>'删除完成'));
	        }else{
	            $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
	        }
		}else{
			$this->error('访问错误');	
		}
	}

	/**
	 * 修改文章分类状态
	 */
	public function status(){
		if(IS_AJAX && !empty(I('post.id'))){
			$status=M('categories')->field('status')->find(I('post.id'))['status']?0:1;
			if(M('categories')->save(array('id'=>I('post.id'),'status'=>$status))){
	            $this->ajaxReturn(array('status'=>1,'msg'=>'修改完成','data'=>$status));
	        }else{
	            $this->ajaxReturn(array('status'=>0,'msg'=>'修改失败'));
	        }
		}else{
			$this->error('访问错误');	
		}
	}
}